/**
 * 目录：
 *  全局变量定义
 *  分类管理相关方法
 *  用户认证相关方法
 *  权限管理相关方法
 *  导航相关方法
 *  搜索相关方法
 *  模态框相关方法
 *  Toast 提示相关方法
 *  生命周期
 *  返回值
 */

const { createApp, ref, computed, onMounted } = Vue;

const app = createApp({
    setup() {
        /// ==================== 全局变量定义 ====================
        //. Token
        let token = localStorage.getItem('token') || null;
        //. Base URL
        const BASE_URL = baseUrl; //. 这里是从url.js引入的baseUrl
        //. 默认headers
        axios.defaults.headers.common['Authorization'] = token;

        /// ==================== 分类管理相关方法 ====================
        
        //. 分类数据
        const groups = ref([]);

        //. 获取分类数据
        const fetchGroups = async () => {
            try {
                const response = await axios.get(`${BASE_URL}/group/getGroupList`);
                if (response.data.code === 200) {
                    groups.value = response.data.data || [];
                } else {
                    showToast('获取分类列表失败', 'error');
                }
            } catch (error) {
                console.error('获取分类列表失败:', error);
                showToast('获取分类列表失败，请稍后重试', 'error');
            }
        };

        //. 编辑分类
        const editGroup = (group) => {
            isEditing.value = true;
            formData.value = {
                id: group.id,
                name: group.name,
                ico: group.ico || ''
            };
            showModal.value = true;
        };

        //. 添加分类
        const addGroup = async () => {
            try {
                const response = await axios.post(`${BASE_URL}/group/addGroup`, {
                    name: formData.value.name,
                    ico: formData.value.ico
                });
                
                if (response.data.code === 200) {
                    showToast('添加分类成功', 'success');
                    closeModal();
                    fetchGroups();
                } else {
                    showToast(response.data.message || '添加分类失败', 'error');
                }
            } catch (error) {
                console.error('添加分类失败:', error);
                showToast('添加分类失败: ' + (error.response?.data?.message || error.message), 'error');
            }
        };

        //. 更新分类
        const updateGroup = async () => {
            try {
                const response = await axios.post(`${BASE_URL}/group/updateGroup`, {
                    id: formData.value.id,
                    name: formData.value.name,
                    ico: formData.value.ico
                });
                
                if (response.data.code === 200) {
                    showToast('更新分类成功', 'success');
                    closeModal();
                    fetchGroups();
                } else {
                    showToast(response.data.message || '更新分类失败', 'error');
                }
            } catch (error) {
                console.error('更新分类失败:', error);
                showToast('更新分类失败: ' + (error.response?.data?.message || error.message), 'error');
            }
        };

        //. 删除分类
        const deleteGroup = async (group) => {
            if (!confirm(`确定要删除分类 "${group.name}" 吗？`)) {
                return;
            }
            
            try {
                const response = await axios.delete(`${BASE_URL}/group/deleteGroup?id=${group.id}`);
                
                if (response.data.code === 200) {
                    showToast('删除分类成功', 'success');
                    fetchGroups();
                } else {
                    showToast(response.data.message || '删除分类失败', 'error');
                }
            } catch (error) {
                console.error('删除分类失败:', error);
                showToast('删除分类失败: ' + (error.response?.data?.message || error.message), 'error');
            }
        };

        //. 保存分类（添加或更新）
        const saveGroup = () => {
            if (!formData.value.name) {
                showToast('请输入分类名称', 'warning');
                return;
            }
            
            if (isEditing.value) {
                updateGroup();
            } else {
                addGroup();
            }
        };

        //. 是否是小屏幕设备
        const isMobile = ref(false);

        //. 核心检测逻辑
        const detect = () => {
            const ua = navigator.userAgent || navigator.vendor || window.opera;
            const hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
            const screenWidth = window.innerWidth || document.documentElement.clientWidth;

            //. 用户代理检测（覆盖主流移动设备）
            const uaPattern = /(android|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|harmony)/i;

            //. 组合判断条件
            isMobile.value = uaPattern.test(ua) && (hasTouch || screenWidth < 768);
        };

        /// ==================== 用户认证相关方法 ====================

        //. 默认用户信息
        const defaultUser = {
            id: 0,
            username: '游客',
            phone: '',
            permission: 0,
            recorddate: '',
            email: '',
            logintime: '',
            collection: ''
        };

        //. 当前用户信息
        const currentUser = ref(defaultUser);

        //. 检查登录状态
        const checkLoginStatus = async () => {
            try {
                // 如果没有token，直接重定向
                if (!token) {
                    showToast('请先登录', 'error');
                    setTimeout(() => {
                        window.location.href = '../../index.html';
                    }, 1500);
                    return;
                }

                //. 获取用户信息
                const response = await axios.post(`${BASE_URL}/user/getUserByToken`);
                
                if (response.data.code === 200) {
                    //. 设置当前用户信息
                    currentUser.value = response.data.data;
                    
                    //. 获取用户权限
                    const userPermission = currentUser.value.permission;
                    
                    //. 判断权限 - 允许管理员(3)、超级管理员(4)和开发者(5)访问
                    if (userPermission === 3 || userPermission === 4 || userPermission === 5) {
                        //. 允许访问，获取数据
                        await fetchGroups();
                        return;
                    } else {
                        //. 其他权限，显示提示并重定向
                        showToast('您没有权限访问此页面', 'error');
                        setTimeout(() => {
                            window.location.href = '../../index.html';
                        }, 1500);
                    }
                } else {
                    //. 获取用户信息失败，重定向到首页
                    showToast('请先登录', 'error');
                    setTimeout(() => {
                        window.location.href = '../../index.html';
                    }, 1500);
                }
            } catch (error) {
                //. 发生错误，重定向到首页
                showToast('系统错误，请稍后重试', 'error');
                setTimeout(() => {
                    window.location.href = '../../index.html';
                }, 1500);
            }
        };

        //. 退出登录
        const logout = async () => {
            try {
                //. 清除本地存储的token
                localStorage.removeItem('token');
                
                //. 清除axios默认headers中的token
                delete axios.defaults.headers.common['Authorization'];
                
                //. 显示退出成功提示
                showToast('已成功退出登录', 'success');
                
                //. 延迟跳转到首页
                setTimeout(() => {
                    window.location.href = '../../index.html';
                }, 1500);
            } catch (error) {
                console.error('退出登录失败:', error);
                showToast('退出登录失败，请重试', 'error');
            }
        };

        /// ==================== 权限管理相关方法 ====================
        //. 获取权限等级文本
        const getPermissionText = (permission) => {
            const permissionMap = {
                0: '游客',
                1: '用户',
                2: '会员',
                3: '管理员',
                4: '超级管理员',
                5: '开发者'
            };
            return permissionMap[permission] || '未知';
        };

        //. 获取权限等级样式类
        const getPermissionClass = (permission) => {
            const classMap = {
                0: 'visitor',
                1: 'user',
                2: 'member',
                3: 'admin',
                4: 'super-admin',
                5: 'developer'
            };
            return classMap[permission] || 'visitor';
        };

        /// ==================== 导航相关方法 ====================
        //. 返回上一级页面
        const goBack = () => {
            window.history.back();
        };

        /// ==================== 搜索相关方法 ====================

        //. 搜索相关变量
        const searchQuery = ref('');
        const isSearching = ref(false);

        //. 搜索分类
        const search = async () => {
            if (!searchQuery.value.trim()) {
                showToast('请输入搜索关键词', 'error');
                return;
            }

            isSearching.value = true;
            try {
                //. 判断输入是否为纯数字
                const isNumeric = /^\d+$/.test(searchQuery.value.trim());
                
                let response;
                if (isNumeric) {
                    //. 如果是纯数字，进行ID查询
                    response = await axios.get(`${BASE_URL}/group/getGroupById?id=${searchQuery.value.trim()}`);
                    if (response.data.code === 200) {
                        //. 将单个结果转换为数组
                        groups.value = response.data.data ? [response.data.data] : [];
                    } else {
                        groups.value = [];
                        showToast('未找到该ID的分类', 'info');
                    }
                } else {
                    //. 如果不是纯数字，进行名称模糊查询
                    response = await axios.get(`${BASE_URL}/group/getGroupByName?name=${encodeURIComponent(searchQuery.value.trim())}`);
                    if (response.data.code === 200) {
                        groups.value = response.data.data;
                        if (groups.value.length === 0) {
                            showToast('未找到匹配的分类', 'info');
                        }
                    } else {
                        groups.value = [];
                        showToast('搜索失败', 'error');
                    }
                }
            } catch (error) {
                console.error('搜索失败:', error);
                showToast('搜索失败，请稍后重试', 'error');
                groups.value = [];
            } finally {
                isSearching.value = false;
            }
        };

        //. 重置搜索
        const resetSearch = async () => {
            searchQuery.value = '';
            await fetchGroups();
        };

        //. 过滤分类数据 - 由于已经在API层面处理了搜索，这里可以简化
        const filteredGroups = computed(() => {
            return groups.value;
        });

        /// ==================== 模态框相关方法 ====================

        //. 显示添加模态框
        const showAddModal = () => {
            formData.value = {
                id: '',
                name: '',
                ico: ''
            };
            isEditing.value = false;
            showModal.value = true;
        };

        //. 关闭模态框
        const closeModal = () => {
            resetModalState();
        };

        //. 模态框相关变量
        const showModal = ref(false);
        const isEditing = ref(false);
        const formData = ref({
            id: '',
            name: '',
            ico: ''
        });

        //. 重置模态框状态的方法
        const resetModalState = () => {
            showModal.value = false;
            isEditing.value = false;
            formData.value = {
                id: '',
                name: '',
                ico: ''
            };
        };

        /// ==================== Toast 提示相关方法 ====================

        //. 存储定时器ID
        let toastTimer = null;

        //. Toast 状态
        const toast = ref({
            show: false,
            message: '',
            type: 'info'
        });

        //. 存储所有活动的弹窗
        const activeToasts = new Set();

        //. 显示 Toast 的函数
        const showToast = (message, type = 'info') => {
            // 创建新的 Toast 元素
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.classList.add(type);
            toast.textContent = message;

            //. 创建独立的容器
            const container = document.createElement('div');
            container.className = 'toast-container';
            container.appendChild(toast);
            document.body.appendChild(container);

            //. 添加到活动弹窗集合
            activeToasts.add(toast);

            //. 触发重排以启动动画
            toast.offsetHeight;

            //. 设置定时器
            const timer = setTimeout(() => {
                //. 添加消失动画
                toast.style.animation = 'slideUpOut 0.3s ease forwards';

                //. 动画结束后移除元素
                toast.addEventListener('animationend', () => {
                    container.remove();
                    activeToasts.delete(toast);
                });
            }, 3000);

            //. 存储定时器ID
            toast.dataset.timerId = timer;
        };

        /// ==================== 生命周期 ====================

        //. 组件挂载时执行
        onMounted(() => {
            checkLoginStatus();
            fetchGroups();
            detect(); //. 检测设备类型
        });

        /// ==================== 返回值 ====================
        return {
            /// ===================== 分类管理相关方法 ====================
            filteredGroups,
            editGroup,
            saveGroup,
            deleteGroup,
            isMobile,
            /// ================= 用户认证相关方法 ====================
            currentUser,
            checkLoginStatus,
            logout,
            /// ================= 权限管理相关方法 ====================
            getPermissionText,
            getPermissionClass,
            /// ==================== 导航相关方法 ====================
            goBack,
            /// ==================== 搜索相关方法 ====================
            searchQuery,
            search,
            resetSearch,
            /// ==================== 模态框相关方法 ====================
            showModal,
            isEditing,
            formData,
            showAddModal,
            closeModal,
            /// ==================== Toast 提示相关方法 ====================
            toast,
            showToast
        };
    }
});

app.mount('#app');

/**
 * 目录：
 *  全局变量定义
 *  分类管理相关方法
 *  用户认证相关方法
 *  权限管理相关方法
 *  导航相关方法
 *  搜索相关方法
 *  模态框相关方法
 *  Toast 提示相关方法
 *  生命周期
 *  返回值
 */